<script setup lang="ts">
import YkYsVideo from '@yk/components/ys-video/YkYsVideo.vue'
import { Search } from '@element-plus/icons-vue'
import { ElTree } from 'element-plus'
import { FrequencyMessage } from '@utils/request/message'
import YkEmptyBox from '@yk/components/empty-box/YkEmptyBox.vue'
import { EmptyEnum } from '@yk/components/empty-box/type'
import YkAsyncComponent from '@yk/components/async-component/YkAsyncComponent.vue'
import lodash from '@utils/lodash'
import { getVideoBySceneTreeAPI } from '@/api/video'
import { AxiosAPIResultType } from '@utils/request/type'
import { ArrayType } from '@/typings'
import { VideoDTO } from '@/api/entity/video'
import { FilterValue } from 'element-plus/es/components/tree/src/tree.type'

defineOptions({ name: 'VideoIndex' })

onMounted(() => {
  getVideoTreeList()
})

// region TODO 分屏
// 分割数量
const splitCount = shallowRef(2)
// 最大显示数量
const splitShowMaxCount = shallowRef(4)
// 视频容器Ref
const videoContainerRef = shallowRef<HTMLDivElement>()

const splitMenuList = [
  { component: import('~icons/video/split1'), splitCount: 1, title: '一分屏' },
  { component: import('~icons/video/split2'), splitCount: 2, title: '四分屏' },
  { component: import('~icons/video/split3'), splitCount: 3, title: '九分屏' },
  { component: import('~icons/video/split4'), splitCount: 4, title: '十六分屏' }
]
function setSplitCount (count: number) {
  splitCount.value = count
  splitShowMaxCount.value = count ** 2
  videoContainerRef.value.style.setProperty('--split-count', count.toString())
}
const splitBtnClickHandle = lodash.throttle((count: number) => {
  setSplitCount(count)
}, 1000)
// endregion

// region TODO 视频树
type VideoTreeNodeType = ArrayType<AxiosAPIResultType<typeof getVideoBySceneTreeAPI>['data']>
const videoTreeList = shallowRef<VideoTreeNodeType[]>([])
const videoTreeRef = shallowRef<InstanceType<typeof ElTree>>()
// 获取设备列表
function getVideoTreeList () {
  getVideoBySceneTreeAPI().then((res) => {
    res.result().then((rdata) => {
      videoTreeList.value = rdata.data || []

      // 检测选中的树节点是否还存在
      // 检测是否存在选中的节点
      if (defaultCheckedKeys.value.length) {
        nextTick(() => {
          // 获取当前勾线的节点
          const checkNodes = videoTreeRef.value.getCheckedNodes() as VideoTreeNodeType[]
          // 过滤掉层级，并存储为Set，方便使用
          const ids = checkNodes.reduce((ret, item) => {
            if (item.isVideo) ret.add(item.value)
            return ret
          }, new Set<string>())
          // 移除不存在的视频
          checkVideoList.value = checkVideoList.value.filter((item) => {
            return ids.has(item.id)
          })
        })
      }

      // 如果树搜索有搜索条件，执行一次搜索
      if (treeFilterText.value) {
        nextTick(() => {
          videoTreeRef.value.filter(treeFilterText.value)
        })
      }
      // PreferenceDB.VideoData.getItem('currentVideo').then((e) => {
      //   if (e) {
      //     const key = 'D' + e
      //     const node = videoTreeRef.value.getNode(key)
      //     if (node) {
      //       setCurrentVideo(node.data)
      //       defaultExpandedKeys.value = [key]
      //       // videoDataState.value = EmptyEnum.SUCCESS
      //     }
      //   }
      // })
    })
  })
}

// region TODO 树搜索
const treeFilterText = ref('')
watch(treeFilterText, (val) => {
  videoTreeRef.value.filter(val)
})
const filterNode = (value: FilterValue, data: VideoTreeNodeType): boolean => {
  if (!value) return true
  return data.label.includes(value)
}
// endregion

// region TODO 树展开
const defaultExpandedKeys = ref<string[]>([])
function treeNodeExpand (e) {
  defaultExpandedKeys.value.push(e.key)
}
function treeNodeCollapse (e) {
  defaultExpandedKeys.value.splice(defaultExpandedKeys.value.findIndex(item => item === e.key), 1)
}
// endregion

// endregion

// region TODO 树 - 隐藏&显示
const isShowTreeBox = shallowRef(true)
function toggleShowTreeBox () {
  isShowTreeBox.value = !isShowTreeBox.value
}
// endregion

// region TODO 选择视频
const defaultCheckedKeys = ref<string[]>([])
// 树选中
function videoTreeCheckChangeHandle (data, checkState) {
  if (data.isVideo) {
    checkState ? checkVideo(data) : uncheckVideo(data)
  }
}
// 点击名称选中
function videoTreeCheckClick (e: any) {
  e.currentTarget.previousElementSibling.click()
}

// 选中的视频列表
const checkVideoList = ref<VideoDTO[]>([])
// 需要显示的设备列表
const showVideoList = computed<VideoDTO[]>(() => {
  if (checkVideoList.value.length <= splitShowMaxCount.value) {
    return checkVideoList.value
  } else {
    return checkVideoList.value.slice(0, splitShowMaxCount.value)
  }
})
const showVideoIdsSet = computed<Set<string>>(() => new Set(showVideoList.value.map(item => item.id)))
// 选中视频
function checkVideo (data: VideoTreeNodeType) {
  if (checkVideoList.value.length < splitShowMaxCount.value) {
    checkVideoList.value.push(data.data)
    defaultCheckedKeys.value.push(data.key)
  } else {
    nextTick(() => {
      videoTreeRef.value.setChecked(data.key, false, false)
    })
    FrequencyMessage.info('视频显示空间已满')
  }
}
// 取消选中视频
function uncheckVideo (data: VideoTreeNodeType) {
  const index = checkVideoList.value.findIndex((item) => item.id === data.value)
  if (index > -1) {
    checkVideoList.value.splice(index, 1)
    defaultCheckedKeys.value.splice(index, 1)
  }
}
// endregion
</script>

<template>
  <div class="layout_view d-flex " style="min-height: 100%;max-height: fit-content;">
    <div class="position-relative">
      <div :style="{ width: isShowTreeBox ? '357px' : 0 }" class="h-100 overflow-hidden" style="transition: all .3s ease-in-out;">
        <div class="pr-12 h-100">
          <div class="c_card-white h-100 " style="width: 345px;">
            <!--分屏-->
            <div class="d-flex-around-center split-menu" style="height: 54px">
              <div
                v-for="(item, index) in splitMenuList" :key="index" class="split-menu__item"
                :class="{ 'is-active': splitCount === item.splitCount }"
                @click="splitBtnClickHandle(item.splitCount)"
              >
                <yk-async-component :is="item.component" class="icon" />
                <span class="title">{{ item.title }}</span>
              </div>
            </div>
            <!--分割线-->
            <el-divider class="mt-20 mb-16" />
            <!--搜索框-->
            <div class="d-flex-between-center">
              <el-input v-model="treeFilterText" class="c_input-search" placeholder="输入名称搜索" :prefix-icon="Search as any" />
              <refresh-btn class="fs-24 color-primary ml-2" @click="getVideoTreeList" />
            </div>
            <!--摄像头树-->
            <el-tree
              ref="videoTreeRef" :data="videoTreeList" show-checkbox
              class="mt-16"
              node-key="key"
              :render-after-expand="false"
              :filter-node-method="filterNode as any"
              :default-expanded-keys="defaultExpandedKeys"
              :default-checked-keys="defaultCheckedKeys"
              @node-expand="treeNodeExpand"
              @node-collapse="treeNodeCollapse"
              @check-change="videoTreeCheckChangeHandle"
            >
              <template #default="{ node, data }">
                <!--摄像头-->
                <div
                  v-if="data.isVideo" class="fs-14 w-100 d-flex align-items-center device-tree__device"
                  :class="{ 'color-primary': showVideoIdsSet.has(data.value) }"
                  @click="videoTreeCheckClick"
                >
                  <ic-device-camera2 class="mr-8" />
                  <span>{{ node.label }}</span>
                </div>
                <!--场景-->
                <div v-else class="fs-14 d-flex-center device-tree__scene">
                  <ic-data-layers class="mr-8" />
                  <span>{{ node.label }}</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
      <collapse-side
        :collapse="!isShowTreeBox" mirroring class="position-absolute"
        :style="{ right: isShowTreeBox ? '-7px' : '-20px' }"
        style="top: 50%;z-index: 9;"
        @click="toggleShowTreeBox"
      />
    </div>

    <yk-empty-box :state="showVideoList.length ? true : { type: EmptyEnum.EMPTY_VAR, description: '请选择要预览的视频' }" :image-size="192" class="flex-1 " :class="{ 'c_card-white': !showVideoList.length }">
      <div ref="videoContainerRef" class="d-grid video-grid h-100">
        <div v-for="item in showVideoList" :key="item.id" class="overflow-hidden position-relative" style="min-height: 300px;">
          <div class="position-absolute wh-100">
            <yk-ys-video
              :ys-video="item" template="pcLive"
              class="wh-100 bor-divider"
            />
          </div>
        </div>
      </div>
    </yk-empty-box>
  </div>
</template>

<style scoped lang="scss">
// 分屏菜单
.split-menu {
  .split-menu__item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    .icon {
      color: #86909C;
      font-size: 28px;
    }
    .title {
      margin-top: 8px;
      font-size: 14px
    }
    &.is-active {
      .icon,.title {
        color: var(--el-color-primary);
      }
    }
  }
}

// 视频网格
.video-grid {
  --split-count: 2;
  grid-template-columns: repeat(var(--split-count), 1fr);
  grid-template-rows: repeat(var(--split-count), 1fr);
  grid-gap: 2px;

}
</style>
